

(function (window) {
	// //继承inherit  Origin 继承 Target
	function inherit(Target, Origin) {
		function F() { };
		F.prototype = Origin.prototype;
		Target.prototype = new F();
		Target.prototype.constructor = Target;
		Target.prototype.uber = Origin.prototype;
	}

	//浅层克隆
	// function clone (origin, target) {
	// 	var target = target || {};
	// 	for(prop in origin) {
	// 		target[prop] = origin[prop];
	// 	}
	// 	return target;
	// }


	// //深层克隆
	// //遍历对象 for...in
	// //1.判断是不是原始值  typeof)() object
	// //2.判断是数组还是对象  instance toString  constructor
	// //3.建立相应的数组或对象
	// //递归
	function deepClone(origin, target) {
		var target = target || {},
			toStr = Object.prototype.toString,
			arrStr = '[object Array]';
		for (var prop in origin) {
			if (origin.hasOwnProperty(prop)) {
				if (origin[prop] !== 'null' && typeof (origin[prop]) == 'object') {
					target[prop] = (toStr.call(origin[prop]) == arrStr) ? [] : {};
					deepClone(origin[prop], target[prop]);
				} else {
					target[prop] = origin[prop];
				}
			}
		}
		return target;
	}

	//my getElementByClass 
	function myGetClass(_className) {
		var allDomArray = document.getElementsByTagName('*');
		var lastDomArray = [];
		function trimSpace(strClass) {
			var reg = /\s+/g;
			var newStrClass = strClass.replace(reg, ' ');
			return newStrClass;
		}
		for (var i = 0; i < allDomArray.length; i++) {
			var lastStrClass = trimSpace(allDomArray[i].className).trim();
			var classArray = lastStrClass.split(' ');
			for (var j = 0; j < classArray.length; j++) {
				if (classArray[j] == _className) {
					lastDomArray.push(classArray[j]);
					break;
				}
			}
		}
		return lastDomArray;
	}
	/**
	 * 
	 * @param {*} selector 选择器  
	 */
	function getEle(selector) {
		var oDom = null;
		var s = slice(selector, 1);
		if (isChar(selector, ".")) {
			oDom = document.getElementsByClassName(s);
		} else if (isChar(selector, "#")) {
			oDom = document.getElementById(s);
		} else {
			oDom = document.getElementsByTagName(selector);
		}
		return oDom;
	}
	function slice(str, st, ed) {
		return str.slice(st, ed)
	}
	function isChar(str, char) {
		if (!str) return false;
		for (var i = 0; i < str.length; i++) {
			if (str[i] == char) return true
		}
		return false;
	}
	//加强版 getElementsByClass  可获取当前元素的所有的class
	function strengthenMyGetClass(_className) {
		_className = _className.split(' ')
		var allDomArray = document.getElementsByTagName('*');
		var lastDomArray = [];
		function trimSpace(strClass) {
			var reg = /\s+/g;
			var newStrClass = strClass.replace(reg, ' ');
			return newStrClass;
		}
		for (var i = 0; i < allDomArray.length; i++) {
			var classStr = trimSpace(allDomArray[i].className).trim();
			var classArr = classStr.split(' ');
			for (var j = 0; j < classArr.length; j++) {
				for (var n = 0; n < _className.length; n++) {
					if (_className.length > 1 && classArr[j] == _className[n]) {
						lastDomArray.push(classArr[j])
					} else if (_className.length === 1 && classArr[j] === _className[n]) {
						lastDomArray.push(classArr[j]);
						break;
					}
				}
			}
		}
		return lastDomArray;
	}

	// //typeof
	function myTypeof(target) {
		var template = {
			"[object Array]": "array",
			"[object Object]": "object",
			"[object Number]": "number - object",
			"[object Boolean]": "boolean - object",
			"[object String]": "string - object"
		};
		if (target == null) {
			return "null"
		} else if (typeof (target) == "object") {
			var str = Object.prototype.toString.call(target);
			return template[str];
		} else {
			return typeof (target);
		}
	}

	//数组去重
	Array.prototype.unique = function () {
		var temp = {};
		var arr = [];
		var len = this.length;
		for (var i = 0; i < len; i++) {
			if (!temp[this[i]]) {
				temp[this[i]] = 'abc';
				arr.push(this[i]);
			}
		}
		return arr;
	}
	// 排序
	Array.prototype.mySort = function () {
		var len = this.length;
		for (var i = 0; i < len - 1; i++) {
			for (var j = i + 1; j < len; j++) {
				if (this[i] > this[j]) {
					var temp = this[i];
					this[i] = this[j];
					this[j] = temp;
				}
			}
		}
	}


	//类数组实现push的方法
	Array.prototype.push = function (target) {
		this[this.length] = target;
		this.length++;
	}


	Array.prototype.myPush = function () {
		for (var i = 0; i < arguments.length; i++) {
			this[this.length] = arguments[i];
		}
		return this.length;
	}
	//获取浏览器窗口大小
	function getViewportOffset() {
		if (window.innerWidth) {
			return {
				w: window.innerWidth,
				h: window.innerHeight
			}
		} else {
			if (document.compatMode == 'BackCompat') {
				return {
					w: document.body.clientWidth,
					h: document.body.clientHeight
				}
			} else {
				return {
					w: document.documentElement.clientWidth,
					h: document.documentElement.clientHeight
				}
			}
		}
	}

	//获取滚动条的滚动的距离
	function getScrollOffset() {
		if (window.pageOffset) {
			return {
				x: pageXOffset,
				y: pageYOffset
			}
		} else {
			return {
				x: document.body.scrollLeft + document.documentElement.scrollLeft,
				y: document.body.scrollTop + document.documentElement.scrollTop
			}
		}
	}


	//封装兼容性方法 getStyle(elem, prop)
	function getStyle(elem, prop) {
		if (window.getComputedStyle) {
			return window.getComputedStyle(elem, null)[prop];
		} else {
			return elem.currentStyle[prop];
		}
	}

	/*
	//自动阅读
	var start = document.getElementsByTagName('div')[i];
	var stop = document.getElementsByTagName('div')[i]；
	var timer = 0;
	var kay = true;
	//var num = 0;
	start.onclick = fucntion () {
		if(key) {
			timer = setInterval(function () {
			  window.scrollBy(0, num);
			},100);
		}
		kay = false;
	}
	stop.onclick = function () {
		clearInterval(timer);
		key = true;
	}
	*/

	//给一个dom对象添加事件处理函数
	function addEvent(elem, type, handle) {
		if (elem.addEventListener) {
			elem.addEventListener(type, handle, false);
		} else if (elem.attachEvent) {
			elem.attachEvent('on' + type, function () {
				handle.call(elem);
			});
		} else {
			elem['on' + type] = handle;
		}
	}

	//取消添加事件
	function removeEvent(elem, type, handle) {
		if (elem.addEventListener) {
			elem.removeEventListener(type, handle, false);
		} else if (elem.attachEvent) {
			elem.detachEvent('on' + type, function () {
				handle.call(elem);
			});
		} else {
			elem['on' + type] = false;
		}
	}

	//封装冒泡
	function stopBubble(event) {
		if (event.stopPropagation) {
			event.stopPropagation();
		} else {
			event.cancelBubble = true;
		}
	}

	//封装阻止默认事件
	function cancelHandler(event) {
		if (event.preventDefault) {
			event.preventDefault();
		} else {
			event.returnValue = false;
		}
	}

	//拖拽
	function darg(elem, callback) {
		var disX,
			disY, top, left;
		addEvent(elem, 'mousedown', function (e) {
			var event = e || window.event;
			disX = event.clientX - parseInt(getStyle(elem, 'left'));
			disY = event.clientY - parseInt(getStyle(elem, 'top'));
			addEvent(document, 'mousemove', mouseMove);
			addEvent(document, 'mouseup', monseUp);
			stopBubble(event);
			cancelHandler(event);
		});
		function mouseMove(e) {
			var event = e || window.event;
			top = event.clientY - disY;
			left = event.clientX - disX;
			elem.style.left = left + "px";
			elem.style.top = top + "px";

			callback && callback(top, left);
		}
		function monseUp(e) {
			var event = e || window.event;
			removeEvent(document, 'mousemove', mouseMove);
			removeEvent(document, 'mouseup', monseUp);
		}
	}

	//异步加载  工具类
	function loadScript(url, callback) {
		var script = document.createElement('script');
		script.type = "text/javascript";
		if (script.readyStyle) {
			script.onreadysrarechange = function () {
				if (script.readyState = 'complete' || script.readyState == 'loaded') {
					callback();
				}
			}
		} else {
			script.onload = function () {
				callback();
			}
		}
		script.src = url;
		document.head.appendChild(script);
	}

	//打印字符串的长度
	function printStrLength(str) {
		var count = 0;
		length = str.length;
		for (var i = 0; i < length; i++) {
			if (str.charCodeAt(i) > 255) {
				count += 2;
			} else {
				count++;
			}
		}
		return count;
	}

	//清除字符串前后空格    兼容所有浏览器
	function trim(str) {
		if (str && typeof str === "string") {
			return str.replace(/(^\s*)|(\s*)$/g, "");//去除前后空白符
		}
	}

	//输出字符串的每一位的个数
	function strPcs(str) {
		var temp = {};
		for (var i = 0, len = str.length; i < len; i++) {
			var key = str[i];
			if (temp[key]) {
				temp[key]++;
			} else {
				temp[key] = 1;
			}
		}
		return JSON.stringify(temp);
	}


	//myIsNaN  判断是否为非数
	function myIsNaN(num) {
		var ret = Number(num);
		ret += '';
		if (ret == 'NaN') {
			return true;
		} else {
			return false;
		}
	}



	//多物体多值链式运动框架
	/**
	 * {
	 * left:0
	 * }
	 * @param {*} obj 
	 * @param {*} json 
	 * @param {*} callback 
	 */
	function startMove(obj, json, callback) {
		clearInterval(obj.timer);
		var iSpeed, iCur;
		obj.timer = setInterval(function () {
			var bStop = true;
			for (var attr in json) {
				if (attr == 'opacity') {
					iCur = parseFloat(getStyle(obj, attr)) * 100;
				} else {
					iCur = parseInt(getStyle(obj, attr));
				}
				iSpeed = (json[attr] - iCur) / 7;
				iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
				if (attr == 'opacity') {
					obj.style.opacity = (iCur + iSpeed) / 100;
				} else {
					obj.style[attr] = iCur + iSpeed + 'px';
				}
				if (iCur != json[attr]) {
					bStop = false;
				}
			}
			if (bStop) {
				clearInterval(obj.timer);
				typeof callback == 'function' ? callback() : '';
			}
		}, 30);
	}

	//防抖函数
	function debounce(hander, delay) {
		var timer = null;
		return function () {
			var _self = this, _arg = arguments;
			clearTimeout(timer);
			timer = setTimeout(function () {
				hander.apply(_self, _arg);
			}, delay);
		}
	}

	//节流函数
	function throttle(hander, warn) {
		var lastTime = 0
		return function () {
			var _self = this; _arg = arguments;
			var nowTime = new Date().getTime();
			if (nowTime - lastTime > warn) {
				hander.apply(_self, _arg);
				lastTime = nowTime;
			}
		}
	}


	/**
	 * myAjax 
	 * @param {*} method GET POST
	 * @param {*} url 
	 * @param {*} data {}
	 * @param {*} callback 请求成功回调
	 * @param {*} flag true 异步 false 同步
	 */
	function myAjax(method, url, data, callback, flag) {
		var xhr = null;
		if (window.XMLHttpRequest) {
			xhr = new XMLHttpRequest();
		} else {
			xhr = new ActiveXObject('Microsoft.XMLHttp');
		}
		method = method.toUpperCase();
		
		if (method == "GET") {
			xhr.open(method, url + '?' + data, flag);
			xhr.send();
		} else {
			xhr.open(method, url, flag);
			xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			xhr.send(data);
		}
		xhr.onreadystatechange = function () {
			if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					callback(xhr.responseText);
				}
			}
		}
	}


	//cookie 增删改查
	var myCookie = {
		set: function (name, value, age) {
			document.cookie = name + '=' + value + ';max-age=' + age;
			return this;
		},
		get: function (name, callback) {
			var cookieArr = document.cookie.split('; ');
			for (var i = 0; i < cookieArr.length; i++) {
				var item = cookieArr[i].split('=');
				if (item[0] === name) {
					callback(item);
					break;
				}
			}
			return this;
		},
		clear: function (name) {
			return this.set(name, '', -1);
		}
	};

	//基于cookie的小球拖拽后保留历史记录
	var move = {
		rect: document.getElementById('rect'),
		init: function () {
			var self = this;
			myCookie.get('top', function (data) {
				data = data == undefined ? 0 : data;
				self.rect.style.top = data + 'px';
			}).get('left', function (data) {
				data = data == undefined ? 0 : data;
				self.rect.style.left = data + 'px';
			});
			this.down();
		},

		down: function () {
			var _this = this;
			this.rect.onmousedown = function (e) {
				_this.disX = e.clientX - this.offsetLeft;
				_this.disY = e.clientY - this.offsetTop;
				document.onmousemove = function (e) {
					_this.x = e.clientX;
					_this.y = e.clientY;
					_this.rect.style.top = _this.y - _this.disY + 'px';
					_this.rect.style.left = _this.x - _this.disX + 'px';
					document.onmouseup = function (e) {
						document.onmousemove = null;
						document.onmouseup = null;
						var rTop = _this.rect.offsetTop,
							rLeft = _this.rect.offsetLeft;
						myCookie.set('top', rTop, 1000000);
						myCookie.set('left', rLeft, 1000000);
					}
				}
			}
		}
	}


	// 判断回文 注：回文字符串：是一个正读和反读都一样的字符串，比如“level”或者“noon”等等就是回文
	function isPlalindrome(str) {
		if (typeof str != "string") return;
		return str.split('').reverse().join('') == str;
	}
	//数字每个{num}(默认3)位加分号
	function formatNum(str, num = 3) {
		var newStr = "";
		var count = 0;
		for (var i = str.length - 1; i >= 0; i--) {
			if (count % num == 0 && count != 0) {
				newStr = str[i] + "," + newStr;
			} else {
				newStr = str[i] + newStr;
			}
			count++;
		}
		return newStr;
	}
	//kb 转 Mb
	function kb2Mb(limit) {
		var size = "";
		if (limit < 0.1 * 1024) { //如果小于0.1KB转化成B
			size = limit.toFixed(2) + "B";
		} else if (limit < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
			size = (limit / 1024).toFixed(2) + "KB";
		} else if (limit < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
			size = (limit / (1024 * 1024)).toFixed(2) + "MB";
		} else { //其他转化成GB
			size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
		}

		var sizestr = size + "";
		var len = sizestr.indexOf("\.");
		var dec = sizestr.substr(len + 1, 2);
		if (dec == "00") {//当小数点后为00时 去掉小数部分
			return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
		}
		return sizestr;
	}
	//时间转换
	function formatterDate(dateText, type = "yyyy-mm-dd hh:mm:ss") {
		if (dateText == "" || dateText == undefined) return;
		var date = new Date(dateText),
			y = date.getFullYear(),
			mon = ("0" + (date.getMonth() + 1)).slice(-2),
			day = ("0" + date.getDate()).slice(-2),
			h = ("0" + date.getHours()).slice(-2),
			m = ("0" + date.getMinutes()).slice(-2),
			s = ("0" + date.getSeconds()).slice(-2);

		var str = '';
		switch (type) {
			case "yyyy-mm-dd hh:mm:ss":
				str = y + "-" + mon + "-" + day + "  " + h + ":" + m + ":" + s; break;
			case "yyyy-mm-dd hh:mm":
				str = y + "-" + mon + "-" + day + "  " + h + ":" + m; break;
			case "yyyy-mm-dd":
				str = y + "-" + mon + "-" + day; break;
			case "yyyy-mm":
				str = y + "-" + mon; break;
			case "hh:mm:ss":
				str = h + ":" + m + ":" + s; break;
			case "hh:mm":
				str = h + ":" + m; break;
			case "yyyy.mm.dd"://2020.08.29
				str = y + "." + mon + '.' + day;
				break;
			case "yyyy.mm.dd hh:mm:ss"://2019.08.27 17:44:25
				str = y + "." + mon + "." + day + "  " + h + ":" + m + ":" + s; break;
		}
		return str;
	}
	/**
	 * 获取图片的base64编码
	 * @param {图片文件} img 
	 * @param {回调} callback 
	 */
	function getImageBase64(img, callback) {
		const reader = new FileReader();
		reader.addEventListener("load", () => callback(reader.result));
		reader.readAsDataURL(img);
	}
    /**
     * copy
     */
    function copy(content) {
        var input = document.createElement("input");
        input.value = content;
        document.body.appendChild(input);
        input.select();
        document.execCommand("copy");
        input.parentNode.removeChild(input);
    }
    /**
     * 设置浏览器title
     */
    const ChangePageTitle = (title) => {
        let userAgentObj = JSON.parse(localStorage.getItem('userAgentObj'))||null
        if(userAgentObj&&userAgentObj.isDingTalk){//钉钉内
            window.$dd.ready(function() {
                window.$dd.biz.navigation.setTitle({
                    title : title,//控制标题文本，空字符串表示显示默认文本
                    onSuccess : function(result) {
                    },
                    onFail : function(err) {}
                });
            });
        }else{//微信或浏览器内
            var $body = $('body');
            document.title = title;//普通浏览器用这一句就可以修改了
            var $iframe = $('<iframe style="display: none"></iframe>');
            $iframe.on('load', function() {
            setTimeout(function() {
                $iframe.off('load').remove();
            }, 0);
            }).appendTo($body);
        }
    }

	var tools = {
		inherit,
		deepClone,
		myGetClass,
		strengthenMyGetClass,
		myTypeof,
		getViewportOffset,
		getScrollOffset,
		getStyle,
		addEvent,
		removeEvent,
		stopBubble,
		cancelHandler,
		darg,
		loadScript,
		printStrLength,
		trim,
		strPcs,
		myIsNaN,
		startMove,
		debounce,
		throttle,
		myAjax,
		myCookie,
		move,
		isPlalindrome,
		formatNum,
		getEle,
		kb2Mb,
		formatterDate,
		getImageBase64,
        copy
	};
	function Tools() {
		this.init();
	}
	Tools.prototype.init = function () {
		for (var props in tools) {
			this[props] = tools[props];
		}
	}
	window.T = new Tools();

})(window)